

import { ScrollView as TaroScrollView, View } from '@tarojs/components'
import { ScrollViewProps as TaroScrollViewProps } from '@tarojs/components/types/ScrollView'
import { Component } from 'react'
import Global from '../lib/global'

import "./scroll-view.scss"

interface ScrollViewProps extends TaroScrollViewProps  {
    footRefresh?: {
        isEnable: boolean,
        refreshText?: string,
        noMoreDataText?: string,
        onRefresh?: (scrollView: ScrollView) => void
    }
}

interface ScrollViewState {
    isFooterRefreshing: boolean,
    isFooterNoMoreData: boolean
}

class ScrollView extends Component<ScrollViewProps, ScrollViewState> {

    footerRefreshText: string
    footerRefreshNoDataText: string
    lowerThreshold: number
    constructor(props: ScrollViewProps) {
        super(props)

        this.footerRefreshText = props.footRefresh?.refreshText ?? "正在加载..."
        this.footerRefreshNoDataText = props.footRefresh?.noMoreDataText ?? "|ﾟρﾟ )ﾉ没有更多了~"

        this.state = {
            isFooterRefreshing: false,
            isFooterNoMoreData: false
        }

        this.lowerThreshold = Global.shared.systemInfo.windowWidth / 750 * 180
    }

    onScrollToLower = (event) => {

        if (this.props.footRefresh?.isEnable == true) {
            if (!this.state.isFooterRefreshing && !this.state.isFooterNoMoreData) {
                this.setState({
                    isFooterRefreshing: true
                })

                if (this.props.footRefresh.onRefresh) {
                    this.props.footRefresh.onRefresh(this)
                }
            }
        }

        if (this.props.onScrollToLower) {
            this.props.onScrollToLower(event)
        }
    }


    endFootRefresh(isNoMoreData?: boolean) {
        this.setState({
            isFooterRefreshing: false,
            isFooterNoMoreData: isNoMoreData ?? false
        })
    }
    

    render() {
        let children = this.props.children
        if (this.props.footRefresh?.isEnable == true) {
            
            let refreshEl = (
                <View className="footer-refresh">
                    <View className="footer-refresh-text">{ (!this.state.isFooterRefreshing && this.state.isFooterNoMoreData) ? this.footerRefreshNoDataText : this.footerRefreshText }</View>
                </View>
            )

            if (children instanceof Array) {
                children.push(refreshEl)
            } else {
                children = [children, refreshEl]
            }
        }

        return (
            <TaroScrollView {...this.props} onScrollToLower={this.onScrollToLower} lowerThreshold={this.lowerThreshold}>
                { children }
            </TaroScrollView>
        )
    }
}

export default ScrollView